package com.mobile.collect.db;

import android.database.Cursor;

import com.github.yuweiguocn.library.greendao.MigrationHelper;
import com.mobile.collect.beans.DeviceInfo;
import com.mobile.collect.beans.DevicePicInfo;
import com.mobile.collect.beans.DevicePointInfo;
import com.mobile.collect.beans.ExportInfo;
import com.mobile.collect.beans.ExportPicInfo;
import com.mobile.collect.beans.ExportResultInfo;
import com.mobile.collect.beans.TypeInfo;

import org.greenrobot.greendao.database.Database;

import java.util.Calendar;
import java.util.List;

import cn.droidlover.xdroidmvp.base.BaseApplication;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;

public class EntityManager {

    private static EntityManager entityManager;
    DaoSession mDaoSession;
    DeviceInfoDao deviceInfoDao;
    DevicePointInfoDao pointInfoDao;
    DevicePicInfoDao picInfoDao;
    ExportResultInfoDao exportResultInfoDao;
    ExportPicInfoDao exportPicInfoDao;
    ExportInfoDao exportInfoDao;
    TypeInfoDao typeInfoDao;

    public EntityManager() {
        DaoMaster.OpenHelper devOpenHelper = new DaoMaster.OpenHelper(BaseApplication.getContext(), "collect-db", null) {
            @Override
            public void onUpgrade(Database db, int oldVersion, int newVersion) {
                //把需要管理的数据库表DAO作为最后一个参数传入到方法中
                MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {
                    @Override
                    public void onCreateAllTables(Database db, boolean ifNotExists) {
                        DaoMaster.createAllTables(db, ifNotExists);
                    }

                    @Override
                    public void onDropAllTables(Database db, boolean ifExists) {
                        DaoMaster.dropAllTables(db, ifExists);
                    }
                }, TypeInfoDao.class, DeviceInfoDao.class, DevicePicInfoDao.class, DevicePointInfoDao.class, ExportResultInfoDao.class, ExportPicInfoDao.class, ExportInfoDao.class);
            }
        };
        DaoMaster mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        mDaoSession = mDaoMaster.newSession();
        deviceInfoDao = mDaoSession.getDeviceInfoDao();
        picInfoDao = mDaoSession.getDevicePicInfoDao();
        pointInfoDao = mDaoSession.getDevicePointInfoDao();
        exportResultInfoDao = mDaoSession.getExportResultInfoDao();
        exportPicInfoDao = mDaoSession.getExportPicInfoDao();
        exportInfoDao = mDaoSession.getExportInfoDao();
        typeInfoDao = mDaoSession.getTypeInfoDao();
    }

    /**
     * 创建单例
     *
     * @return
     */
    public static EntityManager getInstance() {
        if (entityManager == null) {
            entityManager = new EntityManager();
        }
        return entityManager;
    }

    public Long saveDeviceInfo(DeviceInfo info) {
        return deviceInfoDao.insertOrReplace(info);
    }

    public void saveDeviceInfo(List<DeviceInfo> info) {
        deviceInfoDao.insertOrReplaceInTx(info);
    }

    public void uploadDeviceInfo(DeviceInfo info) {
        deviceInfoDao.update(info);
    }

    public DeviceInfo queryDeviceInfoById(Long _ID) {
        mDaoSession.clear();
        return deviceInfoDao.queryBuilder().where(DeviceInfoDao.Properties._ID.eq(_ID)).unique();
    }

    public long queryDeviceInfoCount(Long Id, String deviceName) {
        mDaoSession.clear();
        return deviceInfoDao.queryBuilder().where(DeviceInfoDao.Properties._ID.notEq(Id), DeviceInfoDao.Properties.DeviceName.eq(deviceName)).count();
    }

    public void delDeviceInfo(DeviceInfo deviceInfo) {
        mDaoSession.clear();
        deviceInfoDao.delete(deviceInfo);
        List<DevicePicInfo> list = queryAllDevicePic(deviceInfo.get_ID());
        for (DevicePicInfo picInfo : list) {
            delDevicePicInfo(picInfo);
        }
    }

    public void clearDb() {
        mDaoSession.clear();
        deviceInfoDao.deleteAll();
        picInfoDao.deleteAll();
        pointInfoDao.deleteAll();
    }

    public List<DeviceInfo> queryAllDeviceInfo() {
        mDaoSession.clear();
        return deviceInfoDao.queryBuilder().list();
    }

    public List<DeviceInfo> queryDeviceInfoByName(String name) {
        mDaoSession.clear();
        return deviceInfoDao.queryBuilder().where(DeviceInfoDao.Properties.DeviceName.eq(name)).list();
    }


    public List<DeviceInfo> queryDeviceInfoBy_IDs(List<Long> _IDs) {
        mDaoSession.clear();
        return deviceInfoDao.queryBuilder().where(DeviceInfoDao.Properties._ID.in(_IDs)).list();
    }

    public Long saveDevicePicInfo(DevicePicInfo info) {
        return picInfoDao.insertOrReplace(info);
    }

    public void saveDevicePicInfo(List<DevicePicInfo> list) {
        picInfoDao.insertOrReplaceInTx(list);
    }

    public DevicePicInfo queryDevicePicIById(Long _ID) {
        mDaoSession.clear();
        return picInfoDao.queryBuilder().where(DevicePicInfoDao.Properties._ID.eq(_ID)).unique();
    }

    public void delDevicePicInfo(DevicePicInfo picInfo) {
        mDaoSession.clear();
        picInfoDao.delete(picInfo);
        List<DevicePointInfo> list = queryDevicePointInfoIByParentid(picInfo.get_ID());
        pointInfoDao.deleteInTx(list);
    }

    public void delDevicePicInfo(List<DevicePicInfo> list) {
        mDaoSession.clear();
        picInfoDao.deleteInTx(list);
        for (DevicePicInfo picInfo : list) {
            List<DevicePointInfo> pointlist = queryDevicePointInfoIByParentid(picInfo.get_ID());
            pointInfoDao.deleteInTx(pointlist);
        }

    }

    public List<DevicePicInfo> queryAllDevicePic(Long parentId) {
        mDaoSession.clear();
        List<DevicePicInfo> list = picInfoDao.queryBuilder().where(DevicePicInfoDao.Properties.ParentId.eq(parentId)).orderAsc(DevicePicInfoDao.Properties.SortIndex).list();
        for (DevicePicInfo devicePicInfo : list) {
            NLog.d("queryAllDevicePic",devicePicInfo.getUnitName()+"-"+devicePicInfo.getLabel()+"-sortIndex="+devicePicInfo.getSortIndex());
        }
        return list;
    }

    public List<DevicePicInfo> queryAllDevicePic(Long parentId, int sortIndex) {
        mDaoSession.clear();
        List<DevicePicInfo> list = picInfoDao.queryBuilder().where(DevicePicInfoDao.Properties.ParentId.eq(parentId), DevicePicInfoDao.Properties.SortIndex.ge(sortIndex)).orderAsc(DevicePicInfoDao.Properties.SortIndex).list();
        for (DevicePicInfo devicePicInfo : list) {
            NLog.d("queryAllDevicePic2",devicePicInfo.getUnitName()+"-"+devicePicInfo.getLabel()+"-sortIndex="+devicePicInfo.getSortIndex());
        }
        return list;
    }


    public List<DevicePicInfo> queryAllDeviceUnitByName(Long parentId, String unitName) {
        mDaoSession.clear();
        List<DevicePicInfo> list = picInfoDao.queryBuilder().where(DevicePicInfoDao.Properties.ParentId.eq(parentId), DevicePicInfoDao.Properties.UnitName.eq(unitName)).orderAsc(DevicePicInfoDao.Properties.SortIndex).list();
        for (DevicePicInfo devicePicInfo : list) {
            NLog.d("queryAllDeviceUnitByName",devicePicInfo.getUnitName()+"-"+devicePicInfo.getLabel()+"-sortIndex="+devicePicInfo.getSortIndex());
        }
        return list;
    }

    public List<DevicePicInfo> queryAllDeviceUnit_Gt_sort(Long parentId, String unitName,int sort) {
        mDaoSession.clear();
        return picInfoDao.queryBuilder().where(DevicePicInfoDao.Properties.ParentId.eq(parentId), DevicePicInfoDao.Properties.UnitName.eq(unitName),DevicePicInfoDao.Properties.SortIndex.gt(sort)).orderAsc(DevicePicInfoDao.Properties.SortIndex).list();
    }
    public List<DevicePicInfo> queryAllDeviceUnit_Le_sort(Long parentId, String unitName,int sort) {
        mDaoSession.clear();
        return picInfoDao.queryBuilder().where(DevicePicInfoDao.Properties.ParentId.eq(parentId), DevicePicInfoDao.Properties.UnitName.eq(unitName),DevicePicInfoDao.Properties.SortIndex.le(sort)).orderAsc(DevicePicInfoDao.Properties.SortIndex).list();
    }


    public List<DevicePicInfo> queryAllDevicePic(Long parentId, String name) {
        mDaoSession.clear();
        return picInfoDao.queryBuilder().where(DevicePicInfoDao.Properties.ParentId.eq(parentId), DevicePicInfoDao.Properties.UnitName.eq(name)).orderAsc(DevicePicInfoDao.Properties.SortIndex).list();
    }

    public List<DevicePicInfo> queryAllDevicePic() {
        mDaoSession.clear();
        return picInfoDao.queryBuilder().list();
    }

    public List<DevicePicInfo> queryAllDevicePicByParentIds(List<Long> parentIds) {
        mDaoSession.clear();
        return picInfoDao.queryBuilder().where(DevicePicInfoDao.Properties.ParentId.in(parentIds)).orderDesc(DevicePicInfoDao.Properties.Label).list();
    }

    public DevicePicInfo queryLastDeviceUnitByName(Long parentId, String name) {
        mDaoSession.clear();
        List<DevicePicInfo> list = queryAllDevicePic(parentId, name);
        if (list.size() > 0) {
            return list.get(list.size() - 1);
        } else {
            return null;
        }
    }

    public Long savePointInfo(DevicePointInfo info) {
        NLog.d("savePointInfo", "savePointInfo----111");
        info.setCreateTime(Calendar.getInstance().getTimeInMillis());
        return pointInfoDao.insertOrReplace(info);
    }

    public void savePointInfo(List<DevicePointInfo> list) {
        NLog.d("savePointInfo", "savePointInfo----222");
        for (DevicePointInfo devicePointInfo : list) {
            devicePointInfo.setCreateTime(Calendar.getInstance().getTimeInMillis());
        }

        pointInfoDao.insertOrReplaceInTx(list);
    }

    public DevicePointInfo queryDevicePointInfoIById(Long _ID) {
        mDaoSession.clear();
        return pointInfoDao.queryBuilder().where(DevicePointInfoDao.Properties._ID.eq(_ID)).unique();
    }

    public long queryDevicePointInfoByDeviceId(Long deviceId) {
        mDaoSession.clear();

        String sql1 = "select count(*) from " + pointInfoDao.getTablename() + " as t"
                + " where t." + DevicePointInfoDao.Properties.ParentId.columnName
                + " in (select k." + DevicePicInfoDao.Properties._ID.columnName
                + " from " + picInfoDao.getTablename() + " as k"
                + " where k." + DevicePicInfoDao.Properties.ParentId.columnName + "=" + deviceId
                + ") and t." + DevicePointInfoDao.Properties.ChildTypeEn.columnName + " != 'KP'";


        String sql2 = "select sum(" + DevicePointInfoDao.Properties.DeviceCount.columnName +
                ") from " + pointInfoDao.getTablename() + " as t"
                + " where t." + DevicePointInfoDao.Properties.ParentId.columnName
                + " in (select k." + DevicePicInfoDao.Properties._ID.columnName
                + " from " + picInfoDao.getTablename() + " as k"
                + " where k." + DevicePicInfoDao.Properties.ParentId.columnName + "=" + deviceId
                + ") and t." + DevicePointInfoDao.Properties.ChildTypeEn.columnName + " = 'KP'";

//                + "and t." + DevicePointInfoDao.Properties.ChildTypeEn.columnName + " = 'KP'";

        Cursor cursor1 = mDaoSession.getDatabase().rawQuery(sql1, null);
        Cursor cursor2 = mDaoSession.getDatabase().rawQuery(sql2, null);


        NLog.d("Cursor", sql1);
        NLog.d("Cursor", sql2);
        long count1 = 0;


        if (cursor1 != null && cursor1.moveToFirst()) {
            do {
                count1 = cursor1.getLong(0);
                NLog.d("Cursor", "设备非空冷=" + count1);
            } while (cursor1.moveToNext());
//            count1 = cursor1.getLong(0);
//            NLog.d("Cursor", "点的picID=" + cursor1.getLong(1));
        }
        long count2 = 0;
        if (cursor2 != null && cursor2.moveToFirst()) {
            do {
                count2 = cursor2.getLong(0);
                NLog.d("Cursor", "设备空冷数=" + count2);
            } while (cursor2.moveToNext());
        }

        return count1 + count2;
    }

    public long queryDevicePointInfosByPicId(Long picInfoId) {
        mDaoSession.clear();
        String sql1 = "select count(*) from " + pointInfoDao.getTablename() + " where "
                + DevicePicInfoDao.Properties.ParentId.columnName + "=" + picInfoId
                + " and "
                + DevicePointInfoDao.Properties.ChildTypeEn.columnName + " != 'KP'";

        String sql2 = "select sum(" + DevicePointInfoDao.Properties.DeviceCount.columnName
                + ") from " + pointInfoDao.getTablename() + " where "
                + DevicePicInfoDao.Properties.ParentId.columnName + "=" + picInfoId
                + " and "
                + DevicePointInfoDao.Properties.ChildTypeEn.columnName + " = 'KP'";
        NLog.d("Cursor", sql1);
        NLog.d("Cursor", sql2);
        Cursor cursor1 = mDaoSession.getDatabase().rawQuery(sql1, null);
        Cursor cursor2 = mDaoSession.getDatabase().rawQuery(sql2, null);
        long count1 = 0;
        if (cursor1 != null && cursor1.moveToFirst()) {
            count1 = cursor1.getLong(0);
            NLog.d("Cursor", "count1=" + count1);
        }
        long count2 = 0;
        if (cursor2 != null && cursor2.moveToFirst()) {
            count2 = cursor2.getLong(0);
            NLog.d("Cursor", "count2=" + count2);
        }
        return count1 + count2;
    }

    public List<DevicePointInfo> queryDevicePointInfo() {
        mDaoSession.clear();
        return pointInfoDao.queryBuilder().list();
    }

    public List<DevicePointInfo> queryDevicePointInfoByParents(List<Long> parentIds) {
        mDaoSession.clear();

        return pointInfoDao.queryBuilder().where(DevicePointInfoDao.Properties.ParentId.in(parentIds)).list();
    }

    public void delDevicePointInfo(DevicePointInfo pointInfo) {
        NLog.d("delDevicePointInfo", pointInfo.toString());
        pointInfoDao.delete(pointInfo);
    }

    public void delDevicePointInfoById(long _ID) {
        pointInfoDao.deleteByKey(_ID);
    }

    public void delDevicePointInfo(List<DevicePointInfo> list) {
//        for (DevicePointInfo devicePointInfo : list) {
//            delDevicePointInfo(devicePointInfo);
//        }
        pointInfoDao.deleteInTx(list);
    }

    public void delExportResultInfo(List<ExportResultInfo> list) {
        exportResultInfoDao.deleteInTx(list);
    }

    public List<ExportResultInfo> queryExportResultInfo(Long exportInfoId, String exportTime) {
        List<ExportResultInfo> list = exportResultInfoDao.queryBuilder().where(ExportResultInfoDao.Properties.ParentId.eq(exportInfoId), ExportResultInfoDao.Properties.ExportTime.eq(exportTime)).list();
        if (Kits.Empty.check(list)) {
            return exportResultInfoDao.queryBuilder().where(ExportResultInfoDao.Properties.ParentId.eq(exportInfoId)).list();
        } else {
            return list;
        }
    }

    public List<ExportResultInfo> queryExportResultList() {
        return exportResultInfoDao.queryBuilder().list();

    }

    public void saveExportResultInfo(List<ExportResultInfo> list) {
        exportResultInfoDao.insertInTx(list);
    }

    public void saveExportResultInfo(ExportResultInfo info) {
        exportResultInfoDao.insertOrReplace(info);
    }

    public void delExportInfo(List<ExportInfo> list) {
        exportInfoDao.deleteInTx(list);
    }

    public void saveExportPicInfo(List<ExportPicInfo> list) {
        exportPicInfoDao.insertInTx(list);
    }

    public Long saveExportInfo(ExportInfo exportInfo) {
        return exportInfoDao.insert(exportInfo);
    }

    public List<ExportInfo> queryExportInfo() {
        mDaoSession.clear();
        return exportInfoDao.queryBuilder().list();
    }

    public List<DevicePointInfo> queryDevicePointInfoIByParentid(Long parentId) {
        mDaoSession.clear();
        long count = pointInfoDao.queryBuilder().count();
        return pointInfoDao.queryBuilder().where(DevicePointInfoDao.Properties.ParentId.eq(parentId)).list();
    }

    public List<DevicePointInfo> queryDevicePointInfoIByParentid(Long parentId, boolean isNew) {
        mDaoSession.clear();
        return pointInfoDao.queryBuilder().where(DevicePointInfoDao.Properties.ParentId.eq(parentId), DevicePointInfoDao.Properties.IsNewPoint.eq(isNew)).list();
    }

    public long queryDevicePointByName(Long parentId, String expendNo) {
        mDaoSession.clear();
        return pointInfoDao.queryBuilder().where(DevicePointInfoDao.Properties.ParentId.eq(parentId), DevicePointInfoDao.Properties.ExpendNo.eq(expendNo)).count();
    }

    public void saveTypeInfo(List<TypeInfo> list) {
        delTypeInfo();
        typeInfoDao.insertInTx(list);
    }

    public List<TypeInfo> queryTypeInfos() {
        mDaoSession.clear();
        return typeInfoDao.queryBuilder().list();
    }

    public TypeInfo queryTypeInfo(String childCode) {
//        return typeInfoDao.queryBuilder().where(TypeInfoDao.Properties.ChildCode.eq(childCode)).unique();
        List<TypeInfo> list = typeInfoDao.queryBuilder().where(TypeInfoDao.Properties.ChildCode.eq(childCode)).list();
        if (list.size() == 0) {
            return null;
        } else {
            return list.get(0);
        }

    }

    public void delTypeInfo() {
        typeInfoDao.deleteAll();
    }

}

